package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.controller.BlogController;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import jodd.util.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;
    @Override
    public Result queryBlogById(Long id) {
        //1.查询blog
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("笔记不存在");
        }
        //2.查询用户
        queryBlogUser(blog);
        //3.查询blog是否被当前用户点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user==null){
            blog.setIsLike(false);
            return;
        }
        //1.判断博客是否已经被当前用户点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        blog.setIsLike(score != null);

    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        UserDTO user = UserHolder.getUser();
        if (user==null){
            return Result.fail("请先登录");
        }
        //1.判断博客是否已经被当前用户点赞   可以用ZSst中的查分数方法，若不存在返回nil
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());

        if (score == null){
            //2.未点赞 数据库点赞加一 redis中在set集合加入当前用户
            boolean isSuccess = update().eq("id", id).setSql("liked = liked + 1").update();
            if (isSuccess){
                stringRedisTemplate.opsForZSet().add(key,user.getId().toString(),System.currentTimeMillis());
            }
        }else {
            //3.已点赞 数据库点赞减一 redis在set集合移除当前用户
            boolean isSuccess = update().eq("id", id).setSql("liked = liked - 1").update();
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,user.getId().toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.拉取收件箱
        String key = "feed:"+userId;
        //参数 key min max offset count

        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        //3.解析出博客id minTime作为下一次访问的起点标记，offset，最小的时间戳出现的次数，防止下一次重复访问到当前的最小时间戳
        List<Long> ids = new ArrayList<>(typedTuples.size());
        int os = 1;
        long minTime = 0;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            String idStr = tuple.getValue();
            long time = tuple.getScore().longValue();
            ids.add(Long.valueOf(idStr));
            //计算offset偏移量 作为下一次滚动查询 前端返回给后端
            if (time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        //4.查询博客
        String idstr = StringUtil.join(ids, ",");
        List<Blog> blogList = query().in("id", ids).last("order by Field(id," + idstr + ")").list();

        for (Blog blog : blogList) {
            //查询博客作者以及是否被当前用户点赞
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        //5.返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //Feed流推模式实现 关注用户发送博文推送粉丝 Redis ZSet保存博客id和时间戳 按时间顺序分页获取最新笔记
        // 2.保存探店博文
        boolean success = save(blog);
        if (!success) {
            return Result.fail("新增笔记失败");
        }
        //3.查询所有粉丝
        List<Follow> follow = followService.query().eq("follow_user_id", user.getId()).list();

        //4.给每个粉丝推送笔记id
        for (Follow f : follow) {
            //获取粉丝id
            Long userId = f.getUserId();
            //推送笔记
            String key = "feed:"+userId;
            stringRedisTemplate.opsForZSet()
                    .add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //1.获取点赞前五名用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.解析用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据id查询用户 SELECT id,phone,password,nick_name,icon,create_time,update_time FROM tb_user WHERE id IN ( ? , ? )
        //sql语句用in查询，返回的用户不会根据你给的id顺序排序 需要在结尾添加 order by field(id,5,1...)
        String idstr = StringUtil.join(ids, ",");
        List<UserDTO> userDTOS = userService.query().in("id",ids)
                .last("order by Field(id,"+idstr+")").list()
                .stream().map(user -> {
            return BeanUtil.copyProperties(user, UserDTO.class);
        }).collect(Collectors.toList());
        //4.返回用户
        return Result.ok(userDTOS);
    }

    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
